import 'package:flutter/material.dart';

import 'package:usbflutter/usb/UsbManager.dart';
import 'package:usbflutter/usb/UsbItem.dart';

import 'ConnectPage.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<UsbItem> devices = [];

  int status = 0;

  @override
  void initState() {
    super.initState();
    UsbManager.instance.init();
    _findDevices();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Column(
        children: _buildChildren(),
      ),
      floatingActionButton: FloatingActionButton(
          child: const Text('刷新'),
          onPressed: () {
            _findDevices();
          }),
    );
  }

  /// 查找设备
  void _findDevices() {
    status = 0;
    setState(() {});
    UsbManager.instance.findDevice().then((data) {
      status = 1;
      devices = data;
      setState(() {});
    });
  }

  List<Widget> _buildChildren() {
    List<Widget> list = [
      const SizedBox(
        height: 80,
      )
    ];

    list.add(Container(
        alignment: Alignment.center,
        padding: const EdgeInsets.all(12),
        child: Text(status == 0
            ? '正在查找设备..'
            : devices.isEmpty
                ? '未发现USB设备'
                : '共发现${devices.length}个设备')));
    for (var item in devices) {
      list.add(_buildItem(item));
    }
    return list;
  }

  Widget _buildItem(UsbItem item) {
    return Container(
      padding: const EdgeInsets.all(12),
      margin: const EdgeInsets.all(12),
      decoration: BoxDecoration(
          border: Border.all(color: Colors.black),
          borderRadius: BorderRadius.circular(6)),
      child: Column(
        children: [
          Row(
            children: [
              Text(
                  '设备id: ${item.deviceId}  驱动: ${item.driver == 1 ? '有' : '无'}')
            ],
          ),
          Row(
            children: [
              Expanded(
                  child:
                      Text('供应商id: ${item.vendorId}  产品id: ${item.productId}')),
              SizedBox(
                height: 32,
                child: OutlinedButton(
                    onPressed: () {
                      Navigator.of(context).push(MaterialPageRoute(
                          builder: (b) => ConnectPage(item.deviceId)));
                    },
                    child: const Text(
                      '连接',
                      style: TextStyle(color: Colors.blue),
                    )),
              )
            ],
          ),
        ],
      ),
    );
  }
}
